<template>
  <h3 style="margin-top: 1vh; height: 30px; font-size: large">
    请求Body
    <a-button class="editable-add-btn" type="primary" style="margin: 0 2%; border-radius: 5px; height: 30px" @click="handleAdd"> 新增参数 </a-button>
    <a-button class="editable-add-btn" type="primary" @click="showModal"> Json数据导入 </a-button>
  </h3>

  <a-modal v-model:visible="visible" title="Json数据导入" style="text-align: center" :footer="null">
    <div>
      <p style="float: left; color: red">*</p>
      <p style="float: left">Json数据</p>
    </div>
    <div class="center">
      <a-textarea placeholder="请输入参数对应的Json数据" :rows="13" />
    </div>
    <div class="footer">
      <a-button type="dashed" @click="handleOk">取消</a-button>
      <a-button type="primary" style="margin-left: 10px" @click="handleOk">确认</a-button>
    </div>
  </a-modal>
  <!-- 表格 -->
  <a-table row-key="apcCode" :pagination="false" :columns="columns" :data-source="bodyList" bordered indent-size="40">
    <!-- 整行编辑 -->
    <template #bodyCell="{ column, text, record }">
      <!-- 参数名称 -->
      <template v-if="['apcName'].includes(column.dataIndex)">
        <a-form-item
          v-if="editableData[record.apcCode]"
          :label-col="{
            xs: { span: 0 },
            sm: { span: 0 },
          }"
          :wrapper-col="{
            xs: { span: 24 },
            sm: { span: 24 },
          }"
          :validate-status="editableData[record.apcCode][column.verification].status"
          :help="editableData[record.apcCode][column.verification].message"
        >
          <a-input v-model:value="editableData[record.apcCode][column.dataIndex]" @change="handleChange(editableData[record.apcCode], column.dataIndex)" />
        </a-form-item>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <!-- 默认值、参数描述 -->
      <template v-if="['apcValue', 'apcDescription'].includes(column.dataIndex)">
        <a-form-item v-if="editableData[record.apcCode]">
          <a-input v-model:value="editableData[record.apcCode][column.dataIndex]" />
        </a-form-item>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <!--  数据类型 -->
      <template v-else-if="['apcDataType'].includes(column.dataIndex)">
        <a-form-item
          v-if="editableData[record.apcCode]"
          :label-col="{
            xs: { span: 0 },
            sm: { span: 0 },
          }"
          :wrapper-col="{
            xs: { span: 24 },
            sm: { span: 24 },
          }"
          :validate-status="editableData[record.apcCode][column.verification].status"
          :help="editableData[record.apcCode][column.verification].message"
        >
          <a-select
            v-model:value="editableData[record.apcCode][column.dataIndex]"
            :allow-clear="true"
            style="width: 100%"
            :options="apcDataTypes"
            @change="handleChange(editableData[record.apcCode], column.dataIndex)"
          />
        </a-form-item>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <!--  是否必填 -->
      <template v-else-if="['apcDataNull'].includes(column.dataIndex)">
        <a-form-item
          v-if="editableData[record.apcCode]"
          :label-col="{
            xs: { span: 0 },
            sm: { span: 0 },
          }"
          :wrapper-col="{
            xs: { span: 24 },
            sm: { span: 24 },
          }"
          :validate-status="editableData[record.apcCode][column.verification].status"
          :help="editableData[record.apcCode][column.verification].message"
        >
          <a-select
            v-model:value="editableData[record.apcCode][column.dataIndex]"
            :allow-clear="true"
            style="width: 7vw"
            :options="apcDataNulls"
            @change="handleChange(editableData[record.apcCode], column.dataIndex)"
          />
        </a-form-item>
        <template v-else>
          {{ text }}
        </template>
      </template>

      <template v-else-if="column.dataIndex === 'operation'">
        <div class="save-cancel">
          <!-- 保存--取消 -->
          <template v-if="editableData[record.apcCode]">
            <!-- 保存 -->
            <a-typography-link @click="save(record)"><a-button>保存</a-button></a-typography-link>
            <!-- 取消 -->
            <a-popconfirm title="确定取消吗?" @confirm="cancel(record.apcCode)">
              <a-button>取消</a-button>
            </a-popconfirm>
            <!-- 码值定义 -->
            <template v-if="editableData[record.apcCode].apcDataType == 'String' || editableData[record.apcCode].apcDataType == 'Int'">
              <code-defined />
            </template>
            <!-- 添加下级 -->
            <template v-if="editableData[record.apcCode].apcDataType == 'Object' || editableData[record.apcCode].apcDataType == 'Array'">
              <a-button class="addNext" @click="handleAddChildren(record)">添加下级</a-button>
            </template>
          </template>

          <!-- 编辑--删除 -->
          <template v-else>
            <!-- 编辑 -->
            <a-button type="primary" @click="edit(record)">编辑</a-button>
            <!-- 删除 -->
            <a-popconfirm v-if="bodyList.length" title="确定取消吗？" @confirm="onDelete(record)">
              <a-button type="dashed">删除</a-button>
            </a-popconfirm>
          </template>
        </div>
      </template>
    </template>
  </a-table>
</template>
<script lang="ts" setup>
  import type { UnwrapRef } from 'vue';
  import CodeDefined from './codeDefined.vue';
  import { addingApiParamterConfig } from '@/pages/CodeTables/specification';
  import { cloneDeep } from 'lodash-es';
  import { getInterfaceDetailsHooks } from '@/hooks/InterfaceManagementHooks/getInterfaceDetailsHooks';
  import message from 'ant-design-vue/lib/message';
  // 引入hooks
  const { bodyList, isValid } = getInterfaceDetailsHooks();
  // 表头
  const columns = [
    {
      title: '参数名称',
      dataIndex: 'apcName',
      verification: 'apcNameVerify',
      width: '15%',
      align: 'center',
    },
    {
      title: '数据类型',
      dataIndex: 'apcDataType',
      verification: 'apcDataTypeVerify',
      width: '15%',
      align: 'center',
    },
    {
      title: '是否必填',
      dataIndex: 'apcDataNull',
      verification: 'apcDataNullVerify',
      width: '15%',
      align: 'center',
    },
    {
      title: '默认值',
      dataIndex: 'apcValue',
      width: '10%',
      align: 'center',
    },
    {
      title: '参数描述',
      dataIndex: 'apcDescription',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: '20%',
      align: 'center',
    },
  ];

  //数据类型
  const apcDataTypes = [
    {
      label: 'String',
      value: 'String',
    },
    {
      value: 'Int',
      label: 'Int',
    },
    {
      value: 'Float',
      label: 'Float',
    },
    {
      value: 'Object',
      label: 'Object',
    },
    {
      value: 'Array',
      label: 'Array',
    },
  ];
  //是否必填
  const apcDataNulls = [
    {
      value: '是',
      label: '是',
    },
    {
      value: '否',
      label: '否',
    },
  ];

  const editableData: UnwrapRef<Record<string, addingApiParamterConfig>> = reactive({});
  // 编辑
  const edit = (record: addingApiParamterConfig) => {
    editableData[record.apcCode] = cloneDeep(record);
    console.log(editableData[record.apcCode]);
  };
  // 保存
  const save = (record: addingApiParamterConfig) => {
    let dataIndex = ['apcName', 'apcDataType', 'apcDataNull'];
    const flag = isValid(editableData[record.apcCode], dataIndex);
    if (flag) {
      // Object.assign(record, editableData[record.apcCode]);
      record = { ...record, ...editableData[record.apcCode] };
      delete editableData[record.apcCode];
    } else {
      message.destroy();
      message.error('您还有必填项未填写！');
    }
  };
  // 取消
  const cancel = (apcCode: string) => {
    delete editableData[apcCode];
  };
  // 删除
  const onDelete = (record: addingApiParamterConfig) => {
    console.log(record);
    record.parent
      ? (record.parent.children = record.parent.children?.filter(item => item.apcCode !== record.apcCode))
      : (bodyList.value = bodyList.value.filter(item => item.apcCode !== record.apcCode));
    console.log(record);

    if (record.parent?.children?.length == 0) {
      delete record.parent.children;
    }
  };

  //新增参数
  const handleAdd = () => {
    const newData = {
      apcCode: `${new Date().getTime()}`,
      apcName: ``,
      apcPosition: `body`,
      apcDataType: ``,
      apcDataNull: ``,
      apcValue: ``,
      apcDescription: ``,
      apcDataNullVerify: { message: '', status: 'success' },
      apcDataTypeVerify: { message: '', status: 'success' },
      apcNameVerify: { message: '', status: 'success' },
    };
    bodyList.value.push(newData);
    editableData[newData.apcCode] = newData;
  };

  //添加当前节点子节点
  const handleAddChildren = (record: addingApiParamterConfig) => {
    // Object.assign(record, editableData[record.apcCode]);
    record = { ...record, ...editableData[record.apcCode] };
    // delete editableData[record.apcCode];
    let newData = {
      apcName: ``,
      apcPosition: `body`,
      apcDataType: ``,
      apcDataNull: ``,
      apcValue: ``,
      apcDescription: ``,
      apcParentParamCode: `${record.apcCode}`,
      apcCode: `${new Date().getTime()}`,
      apiCode: '',
      parent: record,
      apcDataNullVerify: { message: '', status: 'success' },
      apcDataTypeVerify: { message: '', status: 'success' },
      apcNameVerify: { message: '', status: 'success' },
    };
    editableData[newData.apcCode] = newData;
    // 判断有无children属性决定是增加还是push。
    'children' in record ? record.children?.push(newData) : (record.children = [newData]);
  };

  // 用户改变输入框是触发验证
  const handleChange = (e: addingApiParamterConfig, dataIndex: string) => {
    isValid(e, [dataIndex]);
  };
  //JSON数据导入
  const visible = ref<boolean>(false);
  const showModal = () => {
    visible.value = true;
  };
  const handleOk = (e: MouseEvent) => {
    console.log(e);
    visible.value = false;
  };
</script>

<style scoped lang="less">
  .save-cancel {
    display: flex;
    justify-content: space-evenly;
  }

  .ant-form-item {
    margin-bottom: 0;

    :deep(.ant-form-item-explain) {
      min-height: 0;
    }
  }
</style>
